/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: Bag
 * Author:   zengjian
 * Date:     2018/9/18 15:42
 * Description: 背包
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package fun.codedesign.jdk.math.algorithm.data;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 〈背包〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/9/18 15:42
 */
public class Bag<Item> implements Iterable<Item> {

    private Item[] items = null;
    private int size;
    private int enlargeCount;

    public Bag() {
        // java不支持泛型数组
        items = (Item[]) new Object[10];
    }

    public void add(Item item) {
        if (size() + 1 > items.length) {
            Item[] enlargeItems = (Item[]) new Object[(int) (items.length * 1.5)];
            System.arraycopy(items, 0, enlargeItems, 0, items.length);
            System.out.println();
            items = enlargeItems;
            enlargeCount++;
            System.out.println("扩容第" + enlargeCount + "次");
        }
        items[size++] = item;

    }

    public boolean isEmpty() {
        return size() == 0;
    }

    public int size() {
        return size;
    }

    @Override
    public Iterator<Item> iterator() {
        return new Bag.NestIterator();
    }

    private class NestIterator implements Iterator<Item> {

        int cusor = -1;

        @Override
        public boolean hasNext() {
            int index = cusor + 1;
            return index <= items.length && items[index] != null;
        }

        @Override
        public Item next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return (Item) items[++cusor];
        }

        @Override
        public void remove() {
            items[cusor] = null;
            System.arraycopy(items, cusor + 1, items, cusor, size() - cusor);
        }
    }
}